#!/usr/bin/python3

"""
pip install easyocr
#/tmp的空间较小
export TMPDIR=.
pip install --no-cache-dir easyocr

yum install tesseract-ocr 

https://cloud.tencent.com/developer/article/2327811
"""

def easyOcr():
    import easyocr

    # 创建OCR对象
    reader = easyocr.Reader(['en', 'zh'])

    # 识别文字
    result = reader.readtext('login.png')

    # 处理识别结果
    for (text, bbox, confidence) in result:
        print(f'Text: {text}, Bbox: {bbox}, Confidence: {confidence}')
        

#dnf install tesseract
# pip install pytesseract Pillow
def tesseract():
    from PIL import Image
    import pytesseract
    from PIL import ImageEnhance

    # 打开图片
    img0 = Image.open("login.png")
    
    # 增强图片对比度
    enhancer = ImageEnhance.Contrast(img0)
    img = enhancer.enhance(2.0)
    # 进行文字识别
    #text = pytesseract.image_to_string(img, "eng")
    text = pytesseract.image_to_string(img, lang='eng', config='--oem 3 --psm 3 -c tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')  
    # 打印识别结果
    for c in text:
        print(f'char: {ord(c)}', end='')
    
    print(f" 识别结果：{len(text)} / {text}")    
    
def ddddOcr():
    import ddddocr
    ocr = ddddocr.DdddOcr(show_ad=False)  # 假设你要识别的是英文和中文的混合验证码
    # from PIL import Image  
    # img = Image.open('login.png')  # 假设验证码图片名为captcha.jpg
    # # 注意：以下代码仅为示例，实际方法名可能不同  
    # text = ocr.classification(img)  # 假设直接使用PIL的Image对象进行识别  
    # 或者，如果ddddocr要求输入图像字节流，你可能需要先将PIL的Image对象转换为字节流  
    # img_bytes = io.BytesIO().getvalue()  # 这里的转换代码是不完整的，仅作示意 
    with open('login.png', 'rb') as f:     # 打开图片
        img_bytes = f.read()             # 读取图片
    text = ocr.classification(img_bytes) 
    # res = ocr.classification(img_bytes)      
    for c in text:
        print(f'char: {ord(c)}', end='')
    
    print(f" 识别结果：{len(text)} / {text}")   
    
#tesseract()
ddddOcr()